<template>
  <view class="page-container w-[750rpx] bg-gray-50 mx-auto">
    <!-- 页面标题 -->
    <view class="page-header bg-[#27c530] text-white p-[30rpx]">
      <text class="text-[32rpx] font-bold">体格检查</text>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar bg-white m-[24rpx] p-[24rpx] rounded-[20rpx] shadow-md">
      <view class="flex gap-[16rpx]">
        <nut-input v-model="searchForm.name" placeholder="搜索姓名" class="flex-1" />
        <nut-button type="primary" class="bg-[#27c530]" @click="searchRecords">搜索</nut-button>
      </view>
    </view>

    <!-- 记录列表 -->
    <view v-if="records.length === 0" class="empty-container flex flex-col justify-center items-center py-[100rpx]">
      <text class="text-[56rpx] mb-[16rpx]">🏥</text>
      <text class="text-[32rpx] text-gray-500 mb-[32rpx]">暂无体格检查记录</text>
      <nut-button type="primary" class="bg-[#27c530]" @click="goAdd">添加第一条</nut-button>
    </view>

    <view v-else class="records-container">
      <view v-for="record in records" :key="record.id" class="record-card bg-white m-[24rpx] rounded-[20rpx] shadow-md overflow-hidden cursor-pointer" @click="goView(record.id)">
        <view class="record-header p-[24rpx] border-b border-gray-100">
          <view class="flex justify-between items-start">
            <view class="flex items-center">
              <view class="w-[80rpx] h-[80rpx] rounded-full bg-blue-50 flex items-center justify-center mr-[20rpx]">
                <IconFont name="icon-examination" class="text-[40rpx] text-[#27c530]" />
              </view>
              <view>
                <text class="text-[28rpx] font-bold text-gray-800">{{ record.name || '未填写姓名' }}</text>
                <text class="text-[24rpx] text-gray-500 block mt-[4rpx]">{{ getSexText(record.sex) }} | {{ record.age || '未填写年龄' }}岁</text>
              </view>
            </view>
            <text class="text-[22rpx] text-gray-500">{{ formatDate(record.createTime) }}</text>
          </view>
        </view>

        <view class="record-content p-[24rpx]">
          <view class="flex flex-wrap gap-[12rpx] mb-[16rpx]">
            <view v-if="record.height" class="px-[12rpx] py-[6rpx] bg-blue-100 rounded-[8rpx]">
              <text class="text-[22rpx] text-blue-700">📏 {{ record.height }}cm</text>
            </view>
            <view v-if="record.weight" class="px-[12rpx] py-[6rpx] bg-green-100 rounded-[8rpx]">
              <text class="text-[22rpx] text-green-700">⚖️ {{ record.weight }}kg</text>
            </view>
            <view v-if="record.bmi" class="px-[12rpx] py-[6rpx] bg-orange-100 rounded-[8rpx]">
              <text class="text-[22rpx] text-orange-700">📊 BMI: {{ record.bmi }}</text>
            </view>
            <view v-if="record.bloodPressure" class="px-[12rpx] py-[6rpx] bg-red-100 rounded-[8rpx]">
              <text class="text-[22rpx] text-red-700">🩺 {{ record.bloodPressure }}</text>
            </view>
            <view v-if="record.heartRate" class="px-[12rpx] py-[6rpx] bg-purple-100 rounded-[8rpx]">
              <text class="text-[22rpx] text-purple-700">💓 {{ record.heartRate }}bpm</text>
            </view>
          </view>

          <view v-if="record.idNumber" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">🆔 身份证号：{{ record.idNumber }}</text>
          </view>

          <view v-if="record.temperature" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">🌡️ 体温：{{ record.temperature }}°C</text>
          </view>

          <view v-if="record.waistCircumference" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">📏 腰围：{{ record.waistCircumference }}cm</text>
          </view>

          <view v-if="record.hipCircumference" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">📏 臀围：{{ record.hipCircumference }}cm</text>
          </view>

          <view v-if="record.waistHipRatio" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">📊 腰臀比：{{ record.waistHipRatio }}</text>
          </view>

          <view v-if="record.bodyFat" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">📊 体脂率：{{ record.bodyFat }}%</text>
          </view>

          <view v-if="record.muscleMass" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">💪 肌肉量：{{ record.muscleMass }}kg</text>
          </view>

          <view v-if="record.boneMass" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">🦴 骨量：{{ record.boneMass }}kg</text>
          </view>

          <view v-if="record.bodyWater" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">💧 体水分：{{ record.bodyWater }}%</text>
          </view>

          <view v-if="record.visceralFat" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">📊 内脏脂肪：{{ record.visceralFat }}</text>
          </view>

          <view v-if="record.note" class="mb-[12rpx]">
            <text class="text-[24rpx] text-gray-600">📝 备注：{{ record.note }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="record-actions p-[24rpx] border-t border-gray-100 flex gap-[16rpx]">
          <nut-button size="small" type="primary" class="flex-1 bg-[#27c530]" @click.stop="goView(record.id)">查看</nut-button>
          <nut-button size="small" type="primary" class="flex-1 bg-[#27c530]" @click.stop="goEdit(record.id)">编辑</nut-button>
          <nut-button size="small" type="danger" class="flex-1" @click.stop="deleteRecord(record.id)">删除</nut-button>
        </view>
      </view>
    </view>

    <!-- 悬浮添加按钮 -->
    <view class="fab-container fixed bottom-[48rpx] right-[48rpx]">
      <nut-button type="success" class="!w-[90rpx] !h-[90rpx] !p-0 flex items-center justify-center !min-w-[90rpx] min-h-[90rpx] rounded-full bg-[#27c530] shadow-lg" @click="goAdd">
        <template #icon>
          <IconFont name="plus" size="24" class="text-[48rpx] text-white" />
        </template>
      </nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { request } from '@/service/request'
import { IconFont } from '@nutui/icons-vue-taro'
import { localStg } from '@/utils'

const records = ref<any[]>([])
const searchForm = reactive({
  recordid: '',
  name: ''
})

onMounted(() => {
  const obj = localStg.get("demographicInfo");
  if(obj){
    searchForm.recordid = obj.recordid;
  }
  loadRecords()
})

async function loadRecords() {
  try {
    console.log("loadRecords---------=======================")
    const result = await request.get<any>('/health_records/demographic_body/demographicBodyInfo/list', {}, {
      useErrMsg: true
    })
    console.log(result, "result---------=======================");
    
    if (result.success.records) {
      records.value = result.success.records || []
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Taro.showToast({ title: '加载数据失败', icon: 'error' })
  }
}

function searchRecords() {
  loadRecords()
}

function formatDate(dateStr: string) {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

function getSexText(sex: string) {
  return sex === '男' ? '男' : sex === '女' ? '女' : '未填写'
}

function goAdd() {
  Taro.navigateTo({
    url: './add'
  })
}

function goEdit(id: string) {
  Taro.navigateTo({
    url: `./edit?id=${id}`
  })
}

function goView(id: string) {
  Taro.navigateTo({
    url: `./view?id=${id}`
  })
}

async function deleteRecord(id: string) {
  try {
    const result = await Taro.showModal({
      title: '确认删除',
      content: '确定要删除这条体格检查记录吗？',
      confirmText: '删除',
      cancelText: '取消'
    })
    
    if (result.confirm) {
      await request.delete(`/health_records/demographic_body/demographicBodyInfo/delete?id=${id}`, {}, {
        useErrMsg: true
      })
      
      Taro.showToast({ title: '删除成功', icon: 'success' })
      loadRecords()
    }
  } catch (error) {
    console.error('删除失败:', error)
    Taro.showToast({ title: '删除失败', icon: 'error' })
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
}

.page-header {
  border-radius: 0 0 20rpx 20rpx;
}

.search-bar {
  border-radius: 20rpx;
}

.record-card {
  transition: all 0.3s ease;
}

.record-card:active {
  transform: scale(0.98);
}

.fab-container {
  z-index: 1000;
}

.empty-container {
  min-height: 400rpx;
}

.records-container {
  padding-bottom: 120rpx;
}
</style>
